const { IconGroup, sequelize, Icon } = require("../../../../models");
module.exports = {
  async saveOrUpdateIconGroup(req, res, next) {
    try {
      const { id } = req.body;
      // 保存或更新用户数据
      return id
        ? await this.updateIconGroup(req, res)
        : await this.saveIconGroup(req, res);
    } catch (error) {
      next(error);
    }
  },

  // 保存分组信息
  async saveIconGroup(req, res) {
    const iconGroupItem = await IconGroup.create(req.body);
    if (!iconGroupItem) throw new Error("图标分组保存失败");
    return res.cc(null, "保存成功");
  },

  // 更新分组信息
  async updateIconGroup(req, res) {
    const iconGroupItem = await checkIconGroupItem(req);

    iconGroupItem.iconGroupName = req.body.iconGroupName;

    const flag = await iconGroupItem.save();

    if (!flag) throw new Error("图标分组更新失败");
    return res.cc(null, "更新成功");
  },

  async getIconGroupList(req, res, next) {
    try {
      const iconGroupList = await IconGroup.findAll({
        include: {
          model: Icon,
          as: "icons",
          attributes: { exclude: ["createTime", "updateTime", "iconGroupId"] },
        },
      });
      return res.cc(iconGroupList);
    } catch (error) {
      next(error);
    }
  },

  // 删除图标分组(同步删除关联的图标)
  async deleteIconGroup(req, res, next) {
    sequelize.transaction(async (t) => {
      try {
        // 校验图标分组是否存在
        await this.checkIconGroupItem(req);

        // 先删除关联的图标
        const iconFlag = await Icon.destroy({
          where: {
            iconGroupId: req.body.id,
          },
          transaction: t,
        });
        if (!iconFlag) throw new Error("图标删除失败");

        // 再删除图标分组
        const params = await IconGroup.destroy({
          where: {
            id: req.body.id,
          },
          transaction: t,
        });

        if (!params) throw new Error("图标组删除失败");

        return res.cc(null, "删除成功");
      } catch (error) {
        next(error);
      }
    });
  },

  // 查询图标分组列表,查询到就返回
  async checkIconGroupItem(req) {
    const { id } = req.body;
    if (!id) throw new Error("图标组id不能为空");

    const iconGroupItem = await IconGroup.findByPk(id);
    if (!iconGroupItem) throw new Error("图标分组不存在");

    return iconGroupItem;
  },
};
